package com.example.demo.mythread;

import java.util.Stack;

public class ReadStack implements Runnable {
    Stack<Integer> myStack;
    public ReadStack(Stack<Integer> myStack){
        this.myStack = myStack;
    }
    int count = 0;
    @Override
    public void run() {
        try {
            Thread.sleep(50);
        }catch (InterruptedException e){
            System.out.println(e.getMessage());
        }
        System.out.println("子线程"+Thread.currentThread().getName()+"开始读取数据");
        while (count<5){
//            堆栈锁
            synchronized (myStack){
//                当堆栈为空，线程进入等待线程池
                if (myStack.empty()){
                    try {
                        myStack.wait();
                    }catch (InterruptedException e){
                        System.out.println(e.getMessage());
                    }
                }
                System.out.println("子线程"+Thread.currentThread().getName()+"读数据："+myStack.pop());
                count++;
//                线程释放
                if(count==5 || myStack.empty()){
                    myStack.notify();
                }


            }

        }
    }
}
